<template>
  <u-upload
    :fileList="getFileList"
    @afterRead="afterRead"
    @delete="deletePic"
    name="Site"
    :capture="capture"
    :disabled="disabled"
    :multiple="multiple"
    :maxCount="maxCount"
  ></u-upload>
</template>

<script>
import { fileUpload, fileRemove } from '@/api/upload'
export default {
  props: {
    value: {
      type: Array,
      default: () => {
        return []
      }
    },
    maxCount: {
      type: Number,
      default: 5
    },
    multiple: {
      type: Boolean,
      default: true
    },
    capture: {
      type: [String, Array],
      default: () => {
        return ['album', 'camera']
      }
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      fileListSite: []
    }
  },
  computed: {
    getFileList: {
      get() {
        return this.value ? this.value : []
      },
      set(v) {
        let data = v
        this.$emit('input', data)
      }
    }
  },
  onLoad() {},
  methods: {
    // 删除图片
    deletePic(event) {
      this.getFileList.splice(event.index, 1)
    },
    // 新增图片
    async afterRead(event) {
      // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file)
      let fileListLen = this.getFileList.length
      lists.map((item) => {
        this.getFileList.push({
          ...item
        })
      })

      uni.showLoading({
        title: '上传中',
        mask: true
      })

      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(lists[i])
        let item = this.getFileList[fileListLen]
        this.getFileList.splice(
          fileListLen,
          1,
          Object.assign(item, {
            url: result
          })
        )
        fileListLen++
      }
      uni.hideLoading()
      this.getFileList = [...this.getFileList]
    },
    uploadFilePromise({ url, type, name }) {
      return new Promise((resolve, reject) => {
        const files = {
          filePath: url,
          name: 'file',
          formData: {
            fileType: type,
            fileName: name
          }
        }
        fileUpload(files).then((res) => {
          if (res.code === 0) {
            let url = res.data
            resolve(url)
          } else {
            uni.showToast({
              title: res.msg,
              icon: 'none',
              duration: 3000
            })
          }
        })
      })
    }
  }
}
</script>
